<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>搜索模块 - 带历史记录</title>
    <link rel="stylesheet" href="/search.css">
</head>
<body>
<div class="container">
    <!-- 搜索区域 -->
    <div class="search-header">
        <h1>搜索模块演示 - 带历史记录</h1>
        <form class="search-form" th:action="@{/search}" method="get">
            <div class="search-input-wrapper">
                <input type="text"
                       class="search-input"
                       name="keyword"
                       id="keywordInput"
                       th:value="${keyword}"
                       placeholder="请输入搜索关键词..."
                       autocomplete="off"
                       oninput="fetchSuggestions()">

                <!-- 搜索建议下拉框 -->
                <div class="search-suggestions" id="searchSuggestions">
                    <!-- 动态生成搜索建议 -->
                </div>
            </div>
            <input type="hidden" name="type" th:value="${type} ?: 'all'">

            <div class="sort-options">
                <select id="sortSelect" name="sort" onchange="this.form.submit()">
                    <option value="time" th:selected="${sort} == 'time'">时间</option>
                    <option value="relevance" th:selected="${sort} == 'relevance'">相关度</option>
                </select>
            </div>

            <button type="submit" class="search-btn">搜索</button>
        </form>

        <div class="search-tabs">
            <a th:href="@{/search(keyword=${keyword}, type='all', page=1, size=4, sort=${sort})}"
               class="tab-btn"
               th:classappend="${type == null or type == 'all'} ? 'active' : ''">全部</a>
            <a th:href="@{/search(keyword=${keyword}, type='content', page=1, size=4, sort=${sort})}"
               class="tab-btn"
               th:classappend="${type == 'content'} ? 'active' : ''">内容</a>
            <a th:href="@{/search(keyword=${keyword}, type='user', page=1, size=4, sort=${sort})}"
               class="tab-btn"
               th:classappend="${type == 'user'} ? 'active' : ''">用户</a>
        </div>

        <!-- 搜索历史面板 -->
        <div class="search-history-panel" th:if="${searchHistory != null and !searchHistory.isEmpty()}">
            <div class="search-history-header">
                <span class="search-history-title">🕒 搜索历史</span>
                <span class="clear-history-btn" id="clearHistoryBtn">清空历史</span>
            </div>
            <div class="search-history-tags" id="historyTags">
                <div class="history-tag"
                     th:each="item : ${searchHistory}"
                     th:attr="data-keyword=${item}">
                    <span th:text="${item}"></span>
                    <span class="remove-tag">×</span>
                </div>
            </div>
        </div>
    </div>

    <!-- 搜索结果区域 -->
    <div class="search-results" th:if="${keyword != null and keyword != ''}">
        <!-- AI智能解释区域 -->
        <div class="ai-explanation-section" th:if="${keyword != null and keyword != ''}" style="margin-bottom: 20px;">
            <div class="ai-explanation-container">
                <div class="ai-explanation-header">
                    <div class="ai-icon">🤖</div>
                    <h3>AI智能解释</h3>
                    <div class="ai-status" id="aiStatus">
                        <span class="loading-spinner" id="loadingSpinner">⏳</span>
                        <span class="status-text" id="statusText">AI正在思考中...</span>
                    </div>
                </div>

                <div class="ai-explanation-content" id="aiExplanationContent">
                    <!-- 服务端渲染的AI解释 -->
                    <div th:if="${aiExplanation != null and aiExplanation.success}"
                         class="ai-explanation-text">
                        <p th:text="${aiExplanation.explanation}"></p>
                    </div>

                    <!-- 错误状态 -->
                    <div th:if="${aiExplanation != null and !aiExplanation.success}"
                         class="ai-explanation-error">
                        <p>💡 AI解释暂时不可用，您可以继续浏览搜索结果</p>
                    </div>

                    <!-- 加载中状态（JavaScript控制） -->
                    <div class="ai-explanation-loading" id="aiExplanationLoading" style="display: none;">
                        <div class="loading-animation">
                            <div class="loading-dot"></div>
                            <div class="loading-dot"></div>
                            <div class="loading-dot"></div>
                        </div>
                        <p>AI正在为您分析关键词...</p>
                    </div>
                </div>
            </div>
        </div>

        <div class="results-header">
            <div class="results-count">
                找到约 <span th:text="${totalCount} ?: 0">0</span> 条结果
                <span th:text="'(搜索: ' + ${keyword} + ')'"></span>
                <span th:if="${totalPages > 0}" th:text="' - 第 ' + ${currentPage} + ' 页，共 ' + ${totalPages} + ' 页'"></span>
            </div>

        </div>

        <!-- 动态渲染搜索结果 -->
        <div class="results-list" th:if="${(contentResults != null and !contentResults.isEmpty()) or (userResults != null and !userResults.isEmpty())}">

            <!-- 内容类型结果 -->
            <div class="result-item" th:each="item : ${contentResults}">
                <span class="result-type content">内容</span>
                <div class="result-title" th:onclick="|location.href='/content/${item.id}'|">
                    <span th:text="${item.title}">标题</span>
                </div>
                <div class="result-description" th:text="${item.summary}">
                    内容摘要...
                </div>
                <div class="result-meta">
                    <span th:text="'作者ID: ' + ${item.authorId}">作者ID: </span>
                    <span th:text="'发布时间: ' + ${#temporals.format(item.createTime, 'yyyy-MM-dd')}">发布时间: </span>
                    <span th:text="'阅读量: ' + ${item.viewCount}">阅读量: </span>
                    <span th:text="'点赞: ' + ${item.likeCount}">点赞: </span>
                </div>
            </div>

            <!-- 用户类型结果 -->
            <div class="result-item" th:each="item : ${userResults}">
                <span class="result-type user">用户</span>
                <div class="user-result">
                    <div class="user-avatar"></div>
                    <div class="user-info">
                        <h3 th:onclick="|location.href='/user/${item.id}'|" th:text="${item.username}">用户名</h3>
                        <p th:text="${item.bio}">个人简介</p>
                        <div class="result-meta">
                            <span th:text="'粉丝: ' + ${item.followerCount}">粉丝: </span>
                            <span th:text="'文章: ' + ${item.articleCount}">文章: </span>
                            <span th:text="'关注: ' + ${item.followingCount}">关注: </span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 无搜索结果提示 -->
        <div class="no-results" th:if="${(contentResults == null or contentResults.isEmpty()) and (userResults == null or userResults.isEmpty())}">
            <div class="no-results-icon">🔍</div>
            <h3>没有找到相关结果</h3>
            <p>请尝试使用其他关键词搜索</p>
        </div>

        <!-- 分页导航 -->
        <div class="pagination" th:if="${totalPages > 1}">
            <!-- 上一页 -->
            <a th:if="${hasPrevious}"
               th:href="@{/search(keyword=${keyword}, type=${type}, page=${currentPage-1}, size=4, sort=${sort})}"
               class="page-btn">
                ‹ 上一页
            </a>
            <span th:unless="${hasPrevious}" class="page-btn disabled">‹ 上一页</span>

            <!-- 页码按钮 -->
            <th:block th:with="startPage=${currentPage <= 3 ? 1 : currentPage - 2},
                         endPage=${currentPage + 2 > totalPages ? totalPages : currentPage + 2}">

                <!-- 第一页 -->
                <a th:if="${startPage > 1}"
                   th:href="@{/search(keyword=${keyword}, type=${type}, page=1, size=4, sort=${sort})}"
                   class="page-btn">1</a>

                <!-- 省略号 -->
                <span th:if="${startPage > 2}" class="page-btn disabled">...</span>

                <!-- 页码范围 -->
                <th:block th:each="pageNum : ${#numbers.sequence(startPage, endPage)}">
                    <a th:if="${pageNum != currentPage}"
                       th:href="@{/search(keyword=${keyword}, type=${type}, page=${pageNum}, size=4, sort=${sort})}"
                       class="page-btn" th:text="${pageNum}">1</a>
                    <span th:if="${pageNum == currentPage}"
                          class="page-btn"
                          style="background: #3498db; color: white; border-color: #3498db;"
                          th:text="${pageNum}">1</span>
                </th:block>

                <!-- 省略号 -->
                <span th:if="${endPage < totalPages - 1}" class="page-btn disabled">...</span>

                <!-- 最后一页 -->
                <a th:if="${endPage < totalPages}"
                   th:href="@{/search(keyword=${keyword}, type=${type}, page=${totalPages}, size=4, sort=${sort})}"
                   class="page-btn" th:text="${totalPages}">10</a>
            </th:block>

            <!-- 下一页 -->
            <a th:if="${hasNext}"
               th:href="@{/search(keyword=${keyword}, type=${type}, page=${currentPage+1}, size=4, sort=${sort})}"
               class="page-btn">
                下一页 ›
            </a>
            <span th:unless="${hasNext}" class="page-btn disabled">下一页 ›</span>

            <!-- 页面信息 -->
            <span class="page-info" th:text="${currentPage} + ' / ' + ${totalPages}">1 / 10</span>
        </div>
    </div>

    <!-- 无搜索时的提示 -->
    <div class="no-search-prompt" th:if="${keyword == null or keyword == ''}">
        <div class="no-search-icon">🔍</div>
        <h3>开始您的搜索</h3>
        <p>请输入关键词开始搜索内容和用户</p>
    </div>
</div>

<script>
    // === 搜索建议功能 ===
    function fetchSuggestions() {
        const keyword = document.getElementById('keywordInput').value;
        const suggestionsContainer = document.getElementById('searchSuggestions');

        if (keyword.length < 2) {
            suggestionsContainer.style.display = 'none';
            return;
        }

        // 同时请求建议和纠错
        Promise.all([
            fetch(`/search/suggestions?keyword=${encodeURIComponent(keyword)}`).then(r => r.json()),
            fetch(`/search/correction?keyword=${encodeURIComponent(keyword)}`).then(r => r.json())
        ]).then(([suggestions, correction]) => {
            currentSuggestionIndex = -1;
            suggestionsContainer.innerHTML = '';

            // 如果有纠错建议，优先显示
            if (correction.needsCorrection && correction.suggestions.length > 0) {
                const correctionItem = document.createElement('div');
                correctionItem.className = 'suggestion-item correction-item';
                correctionItem.style.borderBottom = '2px solid #f39c12';
                correctionItem.innerHTML = `
                <div class="suggestion-text" style="color: #f39c12;">
                    💡 ${correction.message}
                </div>
            `;
                correctionItem.addEventListener('click', () => {
                    document.getElementById('keywordInput').value = correction.suggestions[0];
                    suggestionsContainer.style.display = 'none';
                    document.querySelector('.search-form').submit();
                });
                suggestionsContainer.appendChild(correctionItem);
            }

            // 显示其他建议
            suggestions.forEach(item => {
                const suggestionItem = document.createElement('div');
                suggestionItem.className = 'suggestion-item';
                suggestionItem.innerHTML = `<div class="suggestion-text">${item}</div>`;
                suggestionItem.addEventListener('click', () => {
                    document.getElementById('keywordInput').value = item;
                    suggestionsContainer.style.display = 'none';
                    document.querySelector('.search-form').submit();
                });

                // 鼠标事件处理...
                suggestionItem.addEventListener('mouseover', () => {
                    document.querySelectorAll('.suggestion-item').forEach(item => {
                        item.classList.remove('active');
                    });
                    suggestionItem.classList.add('active');
                    currentSuggestionIndex = Array.from(suggestionItem.parentNode.children).indexOf(suggestionItem);
                });

                suggestionsContainer.appendChild(suggestionItem);
            });

            if (correction.needsCorrection || suggestions.length > 0) {
                suggestionsContainer.style.display = 'block';
            } else {
                suggestionsContainer.style.display = 'none';
            }
        });
    }
    // 全局变量，记录当前选中的建议项索引
    let currentSuggestionIndex = -1;

    // 输入框键盘事件处理
    document.getElementById('keywordInput').addEventListener('keydown', function(e) {
        const suggestions = document.querySelectorAll('.suggestion-item');

        // 按下向下箭头
        if (e.key === 'ArrowDown') {
            e.preventDefault();
            if (suggestions.length > 0) {
                currentSuggestionIndex = (currentSuggestionIndex + 1) % suggestions.length;
                updateSuggestionSelection(suggestions);
            }
        }

        // 按下向上箭头
        else if (e.key === 'ArrowUp') {
            e.preventDefault();
            if (suggestions.length > 0) {
                currentSuggestionIndex = (currentSuggestionIndex - 1 + suggestions.length) % suggestions.length;
                updateSuggestionSelection(suggestions);
            }
        }

        // 按下回车
        else if (e.key === 'Enter') {
            e.preventDefault();
            if (currentSuggestionIndex >= 0 && suggestions.length > 0) {
                const selectedItem = suggestions[currentSuggestionIndex];

                // 检查是否是纠错建议项
                if (selectedItem.classList.contains('correction-item')) {
                    // 纠错项：触发点击事件（会自动填入正确的词并搜索）
                    selectedItem.click();
                } else {
                    // 普通建议项：获取文本内容并搜索
                    const selectedSuggestion = selectedItem.querySelector('.suggestion-text').textContent;
                    document.getElementById('keywordInput').value = selectedSuggestion;
                    document.querySelector('.search-form').submit();
                }
            } else {
                // 没有选中建议项时正常提交表单
                document.querySelector('.search-form').submit();
            }
        }
    });

    // === 历史记录相关功能 ===
    document.addEventListener('DOMContentLoaded', function() {
        // 绑定历史记录点击事件
        document.querySelectorAll('#historyTags .history-tag').forEach(tag => {
            const keyword = tag.getAttribute('data-keyword');

            // 主标签点击事件 - 搜索
            tag.querySelector('span:first-child').addEventListener('click', () => {
                document.getElementById('keywordInput').value = keyword;
                document.querySelector('.search-form').submit();
            });

            // 删除按钮点击事件
            tag.querySelector('.remove-tag').addEventListener('click', (e) => {
                e.stopPropagation();
                removeHistoryItem(e, keyword);
            });
        });

        // 清空历史按钮
        document.getElementById('clearHistoryBtn')?.addEventListener('click', clearAllHistory);
    });

    // 清空所有历史记录
    function clearAllHistory() {
        fetch('/search/history/clear', { method: 'POST' })
            .then(() => {
                document.querySelector('.search-history-panel').style.display = 'none';
            });
    }

    // 更新选中的建议项样式
    function updateSuggestionSelection(suggestions) {
        suggestions.forEach((item, index) => {
            if (index === currentSuggestionIndex) {
                item.classList.add('active');
                // 滚动到可见区域
                item.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
            } else {
                item.classList.remove('active');
            }
        });
    }



    // 删除单个历史记录项
    function removeHistoryItem(event, keyword) {
        fetch('/search/history/remove', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: `keyword=${encodeURIComponent(keyword)}`
        })
            .then(() => {
                const tagElement = event.target.closest('.history-tag');
                tagElement.remove();

                // 如果历史记录为空，隐藏整个面板
                if (document.querySelectorAll('.history-tag').length === 0) {
                    document.querySelector('.search-history-panel').style.display = 'none';
                }
            });
    }

    // === 其他功能 ===
    // 点击页面其他区域关闭搜索建议
    document.addEventListener('click', function(e) {
        const suggestionsContainer = document.getElementById('searchSuggestions');
        const inputWrapper = document.querySelector('.search-input-wrapper');

        if (!inputWrapper.contains(e.target)) {
            suggestionsContainer.style.display = 'none';
        }
    });

    // 搜索结果点击事件
    document.querySelectorAll('.result-title').forEach(title => {
        title.addEventListener('click', function() {
            console.log('点击结果:', this.textContent);
        });
    });

    // 分页按钮禁用处理
    document.querySelectorAll('.page-btn.disabled').forEach(function(btn) {
        btn.addEventListener('click', function(e) {
            e.preventDefault();
            return false;
        });
    });

    // AI解释相关JavaScript
    document.addEventListener('DOMContentLoaded', function() {
        // 检查是否需要异步加载AI解释
        const keyword = document.getElementById('keywordInput').value;
        const aiExplanationContent = document.getElementById('aiExplanationContent');
        const aiStatus = document.getElementById('aiStatus');

        // 如果服务端没有提供AI解释，则异步加载
        if (keyword && !aiExplanationContent.querySelector('.ai-explanation-text, .ai-explanation-error')) {
            loadAiExplanationAsync(keyword);
        } else if (aiExplanationContent.querySelector('.ai-explanation-text')) {
            // 如果已有解释，更新状态
            updateAiStatus('success', 'AI解释完成');
        } else if (aiExplanationContent.querySelector('.ai-explanation-error')) {
            // 如果有错误，更新状态
            updateAiStatus('error', 'AI服务暂时不可用');
        }
    });

    // 异步加载AI解释
    function loadAiExplanationAsync(keyword) {
        const aiExplanationContent = document.getElementById('aiExplanationContent');
        const loadingDiv = document.getElementById('aiExplanationLoading');

        // 显示加载状态
        aiExplanationContent.innerHTML = '';
        loadingDiv.style.display = 'block';
        aiExplanationContent.appendChild(loadingDiv);
        updateAiStatus('loading', 'AI正在思考中...');

        // 发送AJAX请求
        fetch(`/search/ai-explanation?keyword=${encodeURIComponent(keyword)}`)
            .then(response => response.json())
            .then(data => {
                loadingDiv.style.display = 'none';

                if (data.success) {
                    // 成功获取AI解释
                    aiExplanationContent.innerHTML = `
                    <div class="ai-explanation-text">
                        <p>${data.explanation}</p>
                    </div>
                `;
                    updateAiStatus('success', 'AI解释完成');
                } else {
                    // AI解释失败
                    aiExplanationContent.innerHTML = `
                    <div class="ai-explanation-error">
                        <p>💡 AI解释暂时不可用，您可以继续浏览搜索结果</p>
                    </div>
                `;
                    updateAiStatus('error', data.errorMessage || 'AI服务暂时不可用');
                }
            })
            .catch(error => {
                loadingDiv.style.display = 'none';
                aiExplanationContent.innerHTML = `
                <div class="ai-explanation-error">
                    <p>💡 AI解释暂时不可用，您可以继续浏览搜索结果</p>
                </div>
            `;
                updateAiStatus('error', '网络连接异常');
            });
    }

    // 更新AI状态显示
    function updateAiStatus(status, message) {
        const statusText = document.getElementById('statusText');
        const loadingSpinner = document.getElementById('loadingSpinner');

        statusText.textContent = message;

        switch(status) {
            case 'success':
                loadingSpinner.innerHTML = '✅';
                break;
            case 'error':
                loadingSpinner.innerHTML = '❌';
                break;
            case 'loading':
            default:
                loadingSpinner.innerHTML = '⏳';
                break;
        }
    }

</script>
</body>
</html>